<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <br>
    <hr>
    <div>
      <p>
        <el-button type="text" @click="dialogFormVisible = true">
          <el-button type="primary" icon="el-icon-plus" round size="mini">添加用户</el-button>
        </el-button>
      </p>
      <el-table
          show-header:true
          :data="roleList"
          border
          style="width: 100%;padding: 0">
        <el-table-column

            align="center"
            fixed
            prop="id"
            label="id"
            width="100">
        </el-table-column>
        <el-table-column
            align="center"
            prop="name"
            label="角色名称"
            width="220">
        </el-table-column>
        <el-table-column
            prop="description"
            label="角色备注"
            width="350">
        </el-table-column>
        <el-table-column
            prop="sort"
            label="排序"
            width="100">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="300">
          <template slot-scope="scope">
            <el-button type="text" size="small">
              <el-button type="success" icon="el-icon-edit" round size="mini" @click="openUpdateDialog(scope.row)">编辑
              </el-button>
            </el-button>
            <el-button type="text">
              <el-button type="warning" icon="el-icon-delete" round size="mini" @click="openDeleteConfirm(scope.row)">
                删除
              </el-button>
            </el-button>
            <el-button type="text">
              <el-button type="warning" icon="el-icon-delete" round size="mini" @click="setCheckedKeysss(scope.row)">角色权限
              </el-button>
            </el-button>

          </template>
        </el-table-column>
      </el-table>
      <!--   分配角色权限表   -->
      <el-dialog title="分配权限" :visible.sync="dialogTableVisible">
        <el-tree
            :data="dataTree"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps">
        </el-tree>
        <el-button @click="getCheckedKeys()">通过 key 获取</el-button>
      </el-dialog>

      <!-- 添加用户表单 -->
      <el-dialog width="60%" title="新增角色" :visible.sync="dialogFormVisible">
        <div>
          <el-form :inline="true" :model="ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="排序码" prop="sort">
              <el-input v-model="ruleForm.sort"></el-input>
            </el-form-item>
            <el-form-item label="角色备注" prop="description">
              <el-input
                  style="width: 700px"
                  type="textarea"
                  :rows="4"
                  v-model="ruleForm.description">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetForm('ruleForm')">取 消</el-button>
              <el-button type="primary" @click="submitRuleForm()">确 定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>

      <!-- 编辑表单 -->
      <el-dialog width="60%" title="新增角色" :visible.sync="dialogFormVisibleLL">
        <div>
          <el-form :inline="true" :model="editForm" :rules="rules" ref="editForm">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="排序码" prop="sort">
              <el-input v-model="editForm.sort"></el-input>
            </el-form-item>
            <el-form-item label="角色备注" prop="description">
              <el-input
                  style="width: 700px"
                  type="textarea"
                  :rows="4"
                  v-model="editForm.description">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="dialogFormVisibleLL=false">取 消</el-button>
              <el-button type="primary" @click="submitEditForm()">确 定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <!-- 分页控件 -->
    <div style="margin: 10px 0; text-align: right;">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :hide-on-single-page="true"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      data:{
        roleId:'',
        permissionId: []
      },
      dialogTableVisible: false,

      textarea: '',
      /*角色列表数据*/
      roleList: [],

      dialogFormVisible: false,
      dialogFormVisibleLL: false,
      /*新增角色数据*/
      ruleForm: {
        name: '',
        sort: '',
        description: ''
      },
      /*编辑角色数据*/
      editForm: {
        id: '',
        name: '',
        sort: '',
        description: ''
      },

      rules: {
        name: [
          {required: true, message: '请输入类别名称', trigger: 'blur'},
          {min: 2, max: 15, message: '类别名称长度必须在 2 到 15 个字符', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^([0-9]{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是 0~99 之间的数字', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入角色备注', trigger: 'blur'},
          {min: 4, max: 200, message: '角色备注长度必须在 2 到 200 个字符', trigger: 'blur'}
        ]
      },
      dataTree: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      // 分页相关数据
      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      pageSize: 20,
      total: 0
    }
  },
  methods: {

    setCheckedKeysss(role){
      for (let i = 0; i < 2; i++) {
        this.setCheckedKeyss(role);
      }
    },
    setCheckedKeyss(role) {
      let url = 'http://localhost:9090/sys/rolepermission/' + role.id+'/list';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult)
        if (jsonResult.state == 20000) {
          this.data.permissionId = jsonResult.data;
          console.log(this.data.permissionId);
          this.data.roleId=role.id;
          this.dialogTableVisible = true;
          this.setCheckedKeys();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    setCheckedKeys() {
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys(this.data.permissionId);
      }
    },
    /*权限树*/
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys());
      let url = 'http://localhost:9090/sys/rolepermission/' + this.data.roleId + '/addNew';
      console.log('url = ' + url);
      let formData = this.$refs.tree.getCheckedKeys();
      console.log('formData = ' + formData);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '权限添加成功！',
            type: 'success'
          });
          this.dialogTableVisible = false;
          this.loadRoleList();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogTableVisible = false;
              this.loadRoleList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    /*setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3]);
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },*/

    // 切换分页
    changePage(page) {
      this.$router.replace('?page=' + page);
      this.loadRoleList();
    },


    /*打开删除弹窗*/
    openDeleteConfirm(role) {
      let message = '此操作将永久删除【' + role.name + '】类别，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(role);
      }).catch(() => {
      });
    },

    /*确认删除*/
    handleDelete(role) {
      let url = 'http://localhost:9090/sys/role/' + role.id + '/delete/delRole';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除【' + role.name + '】类别成功！',
            type: 'success'
          });
          this.loadRoleList();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },

    /*打开编辑角色对话框*/
    openUpdateDialog(role) {

      let url = 'http://localhost:9090/sys/role/' + role.id;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisibleLL = true;
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },

    /*提交编辑角色表*/
    submitEditForm() {
      let url = 'http://localhost:9090/sys/role/' + this.editForm.id + '/update/upRole';
      console.log('url = ' + url);

      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改角色成功！',
            type: 'success'
          });
          this.dialogFormVisibleLL = false;
          this.loadRoleList();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadRoleList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },

    /*重置表单*/
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editor.txt.clear();
    },

    /*新增角色*/
    submitRuleForm() {
      let url = 'http://localhost:9090/sys/role/insert/addRole';
      console.log('url = ' + url);
      let formData = this.qs.stringify(this.ruleForm);
      console.log('formData = ' + formData);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '新增角色成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadRoleList();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadRoleList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },

    /*显示列表*/
    loadRoleList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = 'http://localhost:9090/sys/role?page=' + page;
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.roleList = jsonResult.data.list;
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },

    // 加载类别树的数据
    loadCategoryTree() {
      let url = 'http://localhost:9090/sys/permission/tree';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.dataTree = jsonResult.data;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    }
  },

  mounted() {
    this.loadRoleList();
    this.loadCategoryTree();
    this.setCheckedKeys();
  }
}
</script>

<style>
.demo-form-inline {
  text-align: center;
}
</style>